package net.nagaseyasuhito.nicola.page;

import javax.persistence.NoResultException;

import net.nagaseyasuhito.nicola.component.ImageUploadField;
import net.nagaseyasuhito.nicola.entity.User;
import net.nagaseyasuhito.nicola.service.UserService;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;

import com.google.inject.Inject;

public class SignUpPage extends BasePage {
	private static final long serialVersionUID = 1L;

	public SignUpPage() {
		this.add(new SignUpForm("signUpForm", new User()));
	}

	private class SignUpForm extends Form {
		private static final long serialVersionUID = 1L;

		@Inject
		private UserService userService;

		public SignUpForm(String id, final User user) {
			super(id, new CompoundPropertyModel(user));

			this.add(new FeedbackPanel("feedback"));
			this.add(new TextField("name").setRequired(true).add(new AbstractValidator() {
				private static final long serialVersionUID = 1L;

				@Override
				protected void onValidate(IValidatable validatable) {
					String name = (String) validatable.getValue();

					try {
						SignUpForm.this.userService.findByName(name);
						this.error(validatable, "userExists");
					}
					catch(NoResultException e) {}
				}
			}));
			this.add(new PasswordTextField("password"));
			this.add(new ImageUploadField("image.byteArray").setRequired(true));
			this.add(new Button("submit") {
				private static final long serialVersionUID = 1L;

				@Inject
				private UserService userService;
				
				@Override
				public void onSubmit() {
					this.userService.signUp(user);

					this.setResponsePage(new FinishPage(user));
				}
			});
		}
	}

	public class FinishPage extends BasePage {
		private static final long serialVersionUID = 1L;

		public FinishPage(final User user) {
		}
	}
}
